﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Telerik.Web.UI;
using System.IO;
using FlexCel.Core;

namespace EXAM
{
    public partial class Learning : System.Web.UI.Page
    {
        string sErr = "";
        const string _singleAns = "Single answers";
        const string _multipleAns = "Multiple answers";
        const string _freeAns = "Free answer";
        const string _orderAns = "Ordering answers";
        const string _dsetName = "dsTestLog";
        string _db = "EXA";
        string _connDes = ConfigurationSettings.AppSettings["strDesConnection"].ToString();
        string _connSrc = "";
        string _pathTemp = "~/Template";
        string _pathReport = "~/Report";
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet dset = new DataSet(_dsetName);
            if (!IsPostBack)
            {
                Session["backlink"] = Request.UrlReferrer.OriginalString;
                if (Request["TestNo"] == null)
                {
                    if (Request["TestID"] != null)
                        Session["TestID"] = Request["TestID"].ToString();
                    else
                    {
                        Response.Redirect("LearnTemplate.aspx");
                    }
                    txtTestID.Text = Session["TestID"].ToString();

                    CreateTest(ref dset);
                    //dset.Tables["dtQuest"].DefaultView.Sort = "Line";
                    //dset.Tables["dtAnswer"].DefaultView.Sort = "Test_Log_Line,Rank";

                }
                else
                {
                    int no = Convert.ToInt32(Request["TestNo"].ToString());
                    GetTest(ref dset, no);
                }
                Session[_dsetName] = null;
                Session[_dsetName] = dset;
                Session["QuestIndex"] = 0;
                mtq_question_container.Visible = false;
                mtq_quiz_results_bubble.Visible = false;
                lbNumofQuest.Text = dset.Tables["dtQuest"].Rows.Count.ToString();
                lbNumOfAns.Text = "0";
                Win_ViewReport.VisibleOnPageLoad = false;
            }

            //if (mtq_question_container.Visible == true)
            //{
            //    dset = Session[_dsetName] as DataSet;
            //    GetResult(dset);
            //}




            //dlAnswer.ItemCreated += new DataListItemEventHandler(dlAnswer_ItemCreated);
        }

        private void GetTest(ref DataSet dset, int no)
        {
            Session[_dsetName] = dset;
            //txtTestID.Text = Session["TestID"].ToString();
            //Session["TestID"] = null;
            BUS.TestControl testCtr = new BUS.TestControl();
            DTO.TestInfo testInf = testCtr.GetByNo(no, ref sErr);
            lbName.Text = testInf.Name;
            lbDescription.Text = testInf.Description;
            lbPassScore.Value = Math.Round(100 * (testInf.Pass_Score / testInf.Max_Score), 2).ToString();
            BUS.Test_LogControl logCtr = new BUS.Test_LogControl();
            //int No = logCtr.Get_ByNo(no, ref sErr);
            txtNo.Text = no.ToString();
            //int iToday = BUS.CommonControl.ConvertDateToInt(DateTime.Today);
            if (!dset.Tables.Contains("dtQuest"))
            {

                DataTable dtQuest = new DataTable();
                dtQuest = logCtr.Get_ByNoScore(no, 0, ref sErr);
                dtQuest.TableName = "dtQuest";
                dtQuest.Columns.Add("IsAnswer", typeof(int));

                foreach (DataRow row in dtQuest.Rows)
                {
                    row["Score"] = 0;
                }
                dset.Tables.Add(dtQuest.Copy());


            }

            GetQuestion(dset, no);
            if (testInf.Random_Question_S || testInf.Random_Question_O)
                dset = RebuildDataSet(dset);

            int[] countAns = new int[dset.Tables["dtQuest"].Rows.Count];
            for (int i = 0; i < countAns.Length; i++)
            {
                countAns[i] = 0;
            }
            Session["CountAns"] = countAns;
        }

        private void GetQuestion(DataSet dset, int no)
        {
            BUS.Test_Log_AnswerControl ansCtr = new BUS.Test_Log_AnswerControl();
            DataTable dtAnswer = ansCtr.GetLogByNoScore(no, 0, ref sErr);
            dtAnswer.TableName = "dtAnswer";
            foreach (DataRow row in dtAnswer.Rows)
            {
                row["Answer_Selected"] = false;
                row["Answer_Order"] = "";
                row["Answer_Text"] = "";
            }
            dset.Tables.Add(dtAnswer.Copy());


        }

        void dlAnswer_ItemCreated(object sender, DataListItemEventArgs e)
        {

        }

        //private string GetLabel(int p)
        //{
        //    switch (p)
        //    {
        //        case 0:
        //            return "a";
        //        case 1:
        //            return "b";
        //        case 2:
        //            return "c";
        //        case 3:
        //            return "a";
        //        case 4:
        //            return "e";
        //        case 5:
        //            return "f";
        //        case 6:
        //            return "g";
        //        default: return "";
        //    }
        //}



        private void SetDataToPage(int index, DataSet dset)
        {
            //DTO.Test_LogInfo inf = new DTO.Test_LogInfo(dset.Tables["dtQuest"].Rows[index]);

            //DataRow[] arrRowQ = dset.Tables["dtQuest"].Select("Line=" + (index + 1));
            if (index == 0)
                btnPrev.Enabled = false;
            else
                btnPrev.Enabled = true;
            if (index == dset.Tables["dtQuest"].Rows.Count - 1)
            {
                btnNext.Enabled = false;
            }
            else btnNext.Enabled = true;

            DataRow questRow = dset.Tables["dtQuest"].Rows[index];
            lbLine.Text = "Question " + questRow["Line"].ToString() + ":";
            lbQuest.Text = questRow["QuestName"].ToString();
            string questType = questRow["QuestType"].ToString();
            lbType.Text = "Question Type : " + questType;
            mtq_stamp_.Attributes["class"] = "mtq_stamp";
            mtq_stamp_.InnerHtml = "";
            DataTable dt = dset.Tables["dtAnswer"].Clone();
            DataRow[] rows = dset.Tables["dtAnswer"].Select("Test_Log_No = " + questRow["No"].ToString() + " and Test_Log_Line = " + questRow["Line"].ToString(), "Rank");

            bool flag = true;
            bool flasans = false;
            foreach (DataRow row in rows)
            {
                BUS.AnswerControl ansCtr = new BUS.AnswerControl();
                DTO.AnswerInfo ansInf = ansCtr.Get(Convert.ToInt64(row["Answer_ID"].ToString()), ref sErr);

                DataRow newrow = dt.NewRow();
                newrow.ItemArray = row.ItemArray;
                dt.Rows.Add(newrow);

                if ((questType == _singleAns) || (questType == _multipleAns))
                {
                    flag = flag & (bool)row["Answer_Selected"] == ansInf.IsRight;
                    if ((bool)row["Answer_Selected"])
                        flasans = true;
                }
                else if (questType == _freeAns)
                {
                    flag = flag & row["Answer_Text"].ToString().ToLower() == ansInf.Text_Answer.ToLower();
                    if (row["Answer_Text"].ToString() != "")
                        flasans = true;
                }
                else if (questType == _orderAns)
                {
                    flag = flag & row["Answer_Order"].ToString().ToLower() == ansInf.Order_Answer.ToLower();
                    if (row["Answer_Order"].ToString() != "")
                        flasans = true;
                }

            }

            dlAnswer.DataSource = dt;
            if (flasans || questRow["IsAnswer"].ToString() == "1")
            {
                dlAnswer.Enabled = false;
                if (flag)
                {
                    mtq_stamp_.Attributes["class"] = "mtq_stamp mtq_correct_stamp";
                    mtq_stamp_.InnerHtml = "CORRECT";
                }
                else
                {
                    mtq_stamp_.Attributes["class"] = "mtq_stamp mtq_wrong_stamp";
                    mtq_stamp_.InnerHtml = "WRONG";
                }
            }
            else dlAnswer.Enabled = true;

            dlAnswer.DataBind();
        }

        private void CreateTest(ref DataSet dset)
        {

            Session[_dsetName] = dset;
            txtTestID.Text = Session["TestID"].ToString();
            Session["TestID"] = null;
            BUS.TestControl testCtr = new BUS.TestControl();
            DTO.TestInfo testInf = testCtr.Get(Convert.ToInt64(txtTestID.Text), ref sErr);
            lbName.Text = testInf.Name;
            lbDescription.Text = testInf.Description;
            lbPassScore.Value = Math.Round(100 * (testInf.Pass_Score / testInf.Max_Score), 2).ToString();
            BUS.Test_LogControl logCtr = new BUS.Test_LogControl();
            int No = logCtr.GetNoTemp(Convert.ToInt64(txtTestID.Text), "TMP");
            txtNo.Text = No.ToString();
            int iToday = BUS.CommonControl.ConvertDateToInt(DateTime.Today);
            if (!dset.Tables.Contains("dtQuest"))
            {

                DataTable dtQuest = new DataTable();
                if (testInf.Random_Question_S || testInf.Random_Question_O)
                    dtQuest = logCtr.GetLogRandByNo(No, ref sErr);
                else
                    dtQuest = logCtr.GetLogByNo(No, ref sErr);
                dtQuest.Columns.Add("IsAnswer", typeof(int));

                dtQuest.TableName = "dtQuest";

                dset.Tables.Add(dtQuest.Copy());

                //DataRelation relat = new DataRelation("reQuest_Ans", new DataColumn[] { dtQuest.Columns["No"], dtQuest.Columns["Line"] }, new DataColumn[] { dtAnswer.Columns["Test_Log_No"], dtAnswer.Columns["Test_Log_Line"] });
                //dset.Relations.Add(relat);
            }
            DTO.UserInfo user = Session["UserGuest"] as DTO.UserInfo;
            foreach (DataRow row in dset.Tables["dtQuest"].Rows)
            {
                row["Creation_Time"] = iToday;
                row["User_ID"] = user.ID;
            }
            //lbMin.Text = testInf.Duration_Time.ToString();
            //lbSec.Text = "00";
            RanDomQuestion(dset, testInf.Random_Answers_S, testInf.Random_Answers_O, No);
            //if (testInf.Random_Question_S || testInf.Random_Question_O)
            dset = RebuildDataSet(dset);

            int[] countAns = new int[dset.Tables["dtQuest"].Rows.Count];
            for (int i = 0; i < countAns.Length; i++)
            {
                countAns[i] = 0;
            }
            Session["CountAns"] = countAns;

        }

        private DataSet RebuildDataSet(DataSet dset)
        {
            DataSet result = dset.Clone();
            int index = 1;
            foreach (DataRow row in dset.Tables["dtQuest"].Rows)
            {
                DataRow newRow = result.Tables["dtQuest"].NewRow();
                newRow.ItemArray = row.ItemArray;
                newRow["Line"] = index;
                DataRow[] arrAnsRow = dset.Tables["dtAnswer"].Select("Test_Log_No = " + row["No"].ToString() + " and Test_Log_Line = " + row["Line"].ToString());
                int indexA = 1;
                foreach (DataRow ansRow in arrAnsRow)
                {
                    DataRow newARow = result.Tables["dtAnswer"].NewRow();
                    newARow.ItemArray = ansRow.ItemArray;
                    newARow["Test_Log_Line"] = index;
                    newARow["Rank"] = indexA;
                    result.Tables["dtAnswer"].Rows.Add(newARow);
                    indexA++;
                }
                result.Tables["dtQuest"].Rows.Add(newRow);
                index++;
            }
            return result;
        }

        private void RanDomQuestion(DataSet dset, bool Random_Answers_S, bool Random_Answers_O, int No)
        {
            if (Random_Answers_S || Random_Answers_O)
            {
                DTO.Test_Log_AnswerInfo tmp = new DTO.Test_Log_AnswerInfo();
                DataTable dtAnswer = tmp.ToDataTable();
                dtAnswer.Columns.Add("AnsName");
                dtAnswer.TableName = "dtAnswer";
                dset.Tables.Add(dtAnswer);
                BUS.AnswerControl ansCtr = new BUS.AnswerControl();
                foreach (DataRow row in dset.Tables["dtQuest"].Rows)
                {
                    int iLine = Convert.ToInt32(row["Line"].ToString());
                    DataTable dt = ansCtr.Get_RandByIDQuestion(Convert.ToInt64(row["Question_ID"].ToString()), ref sErr);
                    foreach (DataRow asnRow in dt.Rows)
                    {
                        tmp = new DTO.Test_Log_AnswerInfo();
                        tmp.Answer_ID = Convert.ToInt64(asnRow["ID"]);
                        tmp.Test_Log_Line = iLine;
                        tmp.Test_Log_No = No;
                        tmp.Answer_Selected = false;
                        tmp.Rank = dt.Rows.IndexOf(row);
                        DataRow tmpRow = tmp.ToDataRow(dset.Tables["dtAnswer"]);
                        tmpRow["AnsName"] = asnRow["Description"];
                        dset.Tables["dtAnswer"].Rows.Add(tmpRow);
                    }
                }
            }
            else
            {
                BUS.Test_Log_AnswerControl ansCtr = new BUS.Test_Log_AnswerControl();
                DataTable dtAnswer = ansCtr.GetLogByNo(No, ref sErr);
                foreach (DataRow asnRow in dtAnswer.Rows)
                {
                    asnRow["Answer_Selected"] = false;
                }
                dtAnswer.TableName = "dtAnswer";
                dset.Tables.Add(dtAnswer.Copy());
            }
        }

        protected void btnPrev_Click(object sender, EventArgs e)
        {
            DataSet dset = Session[_dsetName] as DataSet;
            int index = (int)Session["QuestIndex"];
            if (index != 0)
            {
                SaveSelect(dset, index);
                index--;
                Session["QuestIndex"] = index;
                btnPrev.Enabled = index != 0;
                btnNext.Enabled = index != dset.Tables["dtQuest"].Rows.Count - 1;


                SetDataToPage(index, dset);
                lbExplan.Text = "";
            }

        }

        private void SaveSelect(DataSet dset, int index)
        {
            //DataTable dt = dlAnswer.DataSource as DataTable;
            bool flag = true;
            bool flasans = false;
            DataRow questRow = dset.Tables["dtQuest"].Rows[index];
            foreach (ListViewItem item in dlAnswer.Items)
            {
                CheckBox ckb = (CheckBox)item.FindControl("ckbAnswer");
                RadioButton rb = (RadioButton)item.FindControl("rbAnswer");
                //ckb.Checked = Convert.ToBoolean(row["Answer_Selected"]);
                HiddenField hdNo = (HiddenField)item.FindControl("hdNo");
                TextBox txt = (TextBox)item.FindControl("txtAnswer");
                //hdNo.Value = row["Test_Log_No"].ToString();
                HiddenField hdLine = (HiddenField)item.FindControl("hdLine");
                //hdLine.Value = row["Test_Log_Line"].ToString();
                HiddenField hdAnsID = (HiddenField)item.FindControl("hdAnsID");
                //hdAnsID.Value = row["Answer_ID"].ToString();
                DataRow[] arow = dset.Tables["dtAnswer"].Select("Test_Log_No = " + hdNo.Value + " and Test_Log_Line = " + hdLine.Value + " and Answer_ID = " + hdAnsID.Value);
                //DataRow[] rowQ = dset.Tables["dtQuest"].Select("No = " + hdNo.Value + " and Line = " + hdLine.Value);
                // rowQ[0];
                string questType = questRow["QuestType"].ToString();
                //DTO.Test_Log_AnswerInfo inf = new DTO.Test_Log_AnswerInfo(arow[0]);
                BUS.AnswerControl ansCtr = new BUS.AnswerControl();
                DTO.AnswerInfo ansInf = ansCtr.Get(Convert.ToInt64(arow[0]["Answer_ID"].ToString()), ref sErr);

                if (questType == _singleAns)
                {
                    arow[0]["Answer_Selected"] = rb.Checked;
                    flag = flag & rb.Checked == ansInf.IsRight;
                    if (rb.Checked)
                        flasans = true;
                }
                else if (questType == _multipleAns)
                {
                    arow[0]["Answer_Selected"] = ckb.Checked;
                    flag = flag & ckb.Checked == ansInf.IsRight;
                    if (ckb.Checked)
                        flasans = true;
                }
                else if (questType == _freeAns)
                {
                    arow[0]["Answer_Text"] = txt.Text;
                    flag = flag & txt.Text.ToLower() == ansInf.Text_Answer.ToLower();
                    if (txt.Text != "")
                        flasans = true;
                }
                else if (questType == _orderAns)
                {
                    arow[0]["Answer_Order"] = txt.Text;
                    flag = flag & txt.Text.ToLower() == ansInf.Order_Answer.ToLower();
                    if (txt.Text != "")
                        flasans = true;
                }


                //arow[0]["Answer_Text"] = txt.Text;
            }
            if (flasans)
            {
                int[] countAns = Session["CountAns"] as int[];
                countAns[index] = 1;
            }
            //DataRow[] arrRowQ = dset.Tables["dtQuest"].Select("Line=" + (index + 1));

            questRow["Score"] = flag ? 1 : 0;
            dset.Tables["dtQuest"].AcceptChanges();
            dset.Tables["dtAnswer"].AcceptChanges();

        }
        public string GetValueCheck(object val)
        {
            if (val is Boolean)
            {
                if ((bool)val)
                    return "True";
                else return "False";
            }
            return "False";
        }
        protected void btnNext_Click(object sender, EventArgs e)
        {
            DataSet dset = Session[_dsetName] as DataSet;
            int index = (int)Session["QuestIndex"];
            if (index != dset.Tables["dtQuest"].Rows.Count - 1)
            {
                SaveSelect(dset, index);
                index++;
                Session["QuestIndex"] = index;
                btnPrev.Enabled = index != 0;
                btnNext.Enabled = index != dset.Tables["dtQuest"].Rows.Count - 1;


                SetDataToPage(index, dset);
                lbExplan.Text = "";
            }


        }

        protected void btnStart_Click(object sender, EventArgs e)
        {
            DataSet dset = Session[_dsetName] as DataSet;
            if (mtq_question_container.Visible == false)
            {

                SetDataToPage(0, dset);
                btnStart.Text = "Get Result";
                mtq_question_container.Visible = true;
                if (Request["TestNo"] == null)
                    Session["FlagTest"] = 1;
                //StartTest();
                //RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(btnStart, mtq_quiz_results_bubble);
                //RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(btnStart, dlAnswer);
            }
            else
            {
                GetResult(dset);
            }
        }

        private void GetResult(DataSet dset)
        {
            int index = (int)Session["QuestIndex"];
            SaveSelect(dset, index);
            if (Request["TestNo"] == null)
                sErr = SaveResult(_dsetName);
            double score = Convert.ToDouble(dset.Tables["dtQuest"].Compute("SUM(Score)", ""));
            lbCorrect.Text = score.ToString("N0");
            double rate = Math.Round(100 * score / dset.Tables["dtQuest"].Rows.Count, 2);
            lbScore.Text = Math.Round(100 * score / dset.Tables["dtQuest"].Rows.Count, 2).ToString();
            if (rate < Convert.ToDouble(lbPassScore.Value))
            {
                lbNotes.Text = ConfigurationSettings.AppSettings["MsgFail"];
                imgMsg.ImageUrl = "images/cry.png";
                btnSend.Enabled = btnPrint.Enabled = false;

            }
            else
            {
                lbNotes.Text = ConfigurationSettings.AppSettings["MsgPass"];
                imgMsg.ImageUrl = "images/smile.png";
                btnSend.Enabled = btnPrint.Enabled = true;
            }
            int[] Countans = Session["CountAns"] as int[];
            int total = Convert.ToInt32(dset.Tables["dtQuest"].Compute("SUM(IsAnswer)", ""));

            lbNumOfAns.Text = total.ToString();

            if (sErr == "")
            {
                //StopTest();
                //hdNo.Value = no.ToString();
                dlAnswer.Enabled = false;
                btnHint.Enabled = btnList.Enabled = btnNext.Enabled = btnPrev.Enabled = false;
                Session["QuestIndex"] = null;
                Session["Duration_Time"] = null;
                Session["CountAns"] = null;
                Session["FlagTest"] = null;
                Session[_dsetName] = null;
                //Response.Redirect("TestTemplate.aspx");
            }

            mtq_quiz_results_bubble.Visible = true;
            btnStart.Visible = false;
        }

        private string SaveResult(string _dsetName)
        {
            DataSet dset = Session[_dsetName] as DataSet;
            BUS.Test_LogControl logCtr = new BUS.Test_LogControl();
            long idTest = Convert.ToInt64(dset.Tables["dtQuest"].Rows[0]["Test_ID"]);
            long idUrs = Convert.ToInt64(dset.Tables["dtQuest"].Rows[0]["User_ID"]);
            string type = Convert.ToString(dset.Tables["dtQuest"].Rows[0]["Type"]);
            if (type == "TMP")
                sErr = logCtr.Delete(idTest, idUrs, type);
            BUS.Test_Log_AnswerControl ansCtr = new BUS.Test_Log_AnswerControl();
            int No = logCtr.GetMaxNo() + 1;
            foreach (DataRow row in dset.Tables["dtQuest"].Rows)
            {
                DTO.Test_LogInfo logInf = new DTO.Test_LogInfo(row);
                DTO.UserInfo user = Session["UserGuest"] as DTO.UserInfo;
                if (user == null)
                    Response.Redirect("Login.aspx?hander=save");
                DataRow[] rows = dset.Tables["dtAnswer"].Select("Test_Log_No = " + logInf.No + " and Test_Log_Line = " + logInf.Line);
                for (int i = rows.Length - 1; i >= 0; i--)
                {
                    DataRow rowA = rows[i];
                    DTO.Test_Log_AnswerInfo aInf = new DTO.Test_Log_AnswerInfo(rowA);
                    aInf.Test_Log_No = No;
                    ansCtr.Add(aInf, ref sErr);
                    dset.Tables["dtAnswer"].Rows.Remove(rowA);
                }
                logInf.User_ID = user.ID;
                logInf.No = No;
                //logInf.Type = "";
                logCtr.Add(logInf, ref sErr);

            }
            return sErr;

        }

        protected void btnList_Click(object sender, EventArgs e)
        {
            ShowRadWindow(RadWindowManager2, Win_ViewReport, "./Windows/frmListQ.aspx", new object[] { "" });
        }
        protected void ShowRadWindow(RadWindowManager radManager, RadWindow radWindow, string url, object[] Args)
        {
            RadWindow selectedWindow = radManager.Windows[radManager.Windows.IndexOf(radWindow)];
            selectedWindow.EnableViewState = false;
            selectedWindow.NavigateUrl = ResolveUrl(string.Format(url, Args));
            selectedWindow.VisibleOnPageLoad = true;
        }
        protected void CloseRadWindow(RadWindowManager radManager, RadWindow radWindow)
        {
            RadWindow selectedWindow = radManager.Windows[radManager.Windows.IndexOf(radWindow)];
            selectedWindow.EnableViewState = false;
            selectedWindow.NavigateUrl = "";
            selectedWindow.VisibleOnPageLoad = false;
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            CloseRadWindow(RadWindowManager2, Win_ViewReport);

            if (hdCOMMAND_TYPE.Value != "")
            {
                DataSet dset = Session[_dsetName] as DataSet;
                //for (int i = 0; i < dset.Tables["dtQuest"].Rows.Count; i++)
                //{
                //    if (dset.Tables["dtQuest"].Rows[i]["Line"].ToString() == hdCOMMAND_TYPE.Value)
                //    {
                int i = Convert.ToInt32(hdCOMMAND_TYPE.Value);
                int index = (int)Session["QuestIndex"];
                SaveSelect(dset, index);
                Session["QuestIndex"] = i;

                SetDataToPage(i, dset);
                btnPrev.Enabled = i != 0;
                btnNext.Enabled = i != dset.Tables["dtQuest"].Rows.Count - 1;
                lbExplan.Text = "";
                //break;
                //    }
                //}

            }
            hdCOMMAND_TYPE.Value = "";
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {

        }

        protected void btnHint_Click(object sender, EventArgs e)
        {
            if (lbExplan.Text == "")
            {
                DataSet dset = Session[_dsetName] as DataSet;
                int index = (int)Session["QuestIndex"];
                if (index < dset.Tables["dtQuest"].Rows.Count)
                {
                    long idQuest = Convert.ToInt64(dset.Tables["dtQuest"].Rows[index]["Question_ID"].ToString());
                    BUS.QuestionControl questCtr = new BUS.QuestionControl();
                    DTO.QuestionInfo questInf = questCtr.Get(idQuest, ref sErr);
                    if (questInf.Explanation != "")
                        lbExplan.Text = questInf.Explanation;
                    else lbExplan.Text = "None";
                }
                dlAnswer.Enabled = false;
                dset.Tables["dtQuest"].Rows[index]["IsAnswer"] = 1;
            }
            //else
            //{
            //    if (lbQuestType.Value == _singleAns || lbQuestType.Value == _multipleAns)
            //        foreach (ListViewItem item in dlAnswer.Items)
            //        {
            //            Image img = (Image)item.FindControl("img");
            //            RadioButton rdAnswer = (RadioButton)item.FindControl("rbAnswer");
            //            CheckBox ckbAnswer = (CheckBox)item.FindControl("ckbAnswer");
            //            if (img.ImageUrl != "")
            //            {
            //                img.Visible = true;
            //                rdAnswer.Visible = false;
            //                ckbAnswer.Visible = false;
            //            }
            //        }
            //    else
            //    {
            //        foreach (ListViewItem item in dlAnswer.Items)
            //        {
            //            TextBox txtAnswer = (TextBox)item.FindControl("txtAnswer");
            //            txtAnswer.Text = txtAnswer.Attributes["iscorrect"].ToString();
            //        }
            //    }
            //    //btnHint.Enabled = false;
            //}
        }

        protected void dlAnswer_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item is ListViewDataItem)
            {
                DataSet dset = Session[_dsetName] as DataSet;
                DataRow row = ((DataRowView)((ListViewDataItem)e.Item).DataItem).Row;
                Literal txtNum = (Literal)e.Item.FindControl("txtNum");
                //txtNum.Text = GetLabel(e.Item.ItemIndex);

                TextBox txt = (TextBox)e.Item.FindControl("txtAnswer");


                CheckBox ckb = (CheckBox)e.Item.FindControl("ckbAnswer");
                Image img = (Image)e.Item.FindControl("img");
                RadioButton rb = (RadioButton)e.Item.FindControl("rbAnswer");
                BUS.AnswerControl ansCtr = new BUS.AnswerControl();
                DTO.AnswerInfo ansInf = ansCtr.Get(Convert.ToInt64(row["Answer_ID"].ToString()), ref sErr);
                HiddenField hdNo = (HiddenField)e.Item.FindControl("hdNo");
                hdNo.Value = row["Test_Log_No"].ToString();
                HiddenField hdLine = (HiddenField)e.Item.FindControl("hdLine");
                hdLine.Value = row["Test_Log_Line"].ToString();
                HiddenField hdAnsID = (HiddenField)e.Item.FindControl("hdAnsID");
                hdAnsID.Value = row["Answer_ID"].ToString();

                DataRow[] rowQ = dset.Tables["dtQuest"].Select("No = " + hdNo.Value + " and Line = " + hdLine.Value);
                string questType = rowQ[0]["QuestType"].ToString();

                if ((questType == _singleAns) ||
                 (questType == _multipleAns))
                {
                    if (ansInf.IsRight)
                    {
                        img.ImageUrl = "images/correct.png";

                        ckb.Attributes.Add("iscorrect", "1");
                        rb.Attributes.Add("iscorrect", "1");
                    }
                    else
                    {
                        img.ImageUrl = "images/wrong.png";
                        ckb.Attributes.Add("iscorrect", "0");
                        rb.Attributes.Add("iscorrect", "0");
                    }
                }
                else if (questType == _freeAns)
                {
                    txt.Attributes.Add("iscorrect", ansInf.Text_Answer);
                    img.ImageUrl = "images/noimage.png";
                }
                else if (questType == _orderAns)
                {
                    txt.Attributes.Add("iscorrect", ansInf.Order_Answer);
                    img.ImageUrl = "images/noimage.png";
                }

                //RadButton btnToggle = (RadButton)e.Item.FindControl("btnToggle");
                rb.Checked = Convert.ToBoolean(row["Answer_Selected"]);
                ckb.Checked = Convert.ToBoolean(row["Answer_Selected"]);



                if (questType == _singleAns)
                {
                    string script = "SetUniqueRadioButton('.*dlAnswer.*Quest',this)";
                    rb.Attributes.Add("onclick", script);
                    rb.Attributes.Add("style", "float: left;margin-left: 10px;margin-top: 10px;position: relative;");
                    rb.Visible = true;
                    ckb.Visible = false;
                    txt.Visible = false;
                }
                else if (questType == _multipleAns)
                {
                    string scriptChk = "SetResultCheckBox('.*dlAnswer.*ckbAnswer',this)";
                    ckb.Attributes.Add("onclick", scriptChk);
                    ckb.Attributes.Add("style", "float: left;margin-left: 10px;margin-top: 10px;position: relative;");
                    rb.Visible = false;
                    ckb.Visible = true;
                    txt.Visible = false;
                }
                else if (questType == _freeAns)
                {
                    string scripttxt = "SetResultTextBox('.*dlAnswer.*txtAnswer',this)";
                    //txt.Attributes.Add("onkeyup", scripttxt);
                    txt.Attributes.Add("onBlur", scripttxt);
                    txt.Attributes.Add("style", "float: left;margin-left: 60px;width: 35px;");
                    txt.Height = 35;
                    txt.Width = 800;
                    txt.TextMode = TextBoxMode.MultiLine;
                    txt.Visible = true;
                    rb.Visible = false;
                    ckb.Visible = false;
                    //txt.Visible = false;
                    txt.Text = row["Answer_Text"].ToString();
                }
                else if (questType == _orderAns)
                {
                    string scripttxt = "SetResultTextBox('.*dlAnswer.*txtAnswer',this)";
                    txt.Attributes.Add("onkeyup", scripttxt);
                    txt.Attributes.Add("style", "float: left;margin-top: 10px;width: 35px;");
                    txt.MaxLength = 1;
                    txt.Visible = true;
                    rb.Visible = false;
                    ckb.Visible = false;
                    //txt.Visible = false;
                    txt.Text = row["Answer_Order"].ToString();
                }


            }
        }


        protected void btn_Click(object sender, EventArgs e)
        {
            if (Session["backlink"] != null)
            {
                Response.Redirect(Session["backlink"].ToString());
            }
            else Response.Redirect("LearnTemplate.aspx");
        }

        protected void dlAnswer_ItemCommand(object sender, ListViewCommandEventArgs e)
        {

        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            if (Request["TestID"] != null)
            {
                _pathTemp = MapPath(_pathTemp) + "/";
                _pathReport = MapPath(_pathReport) + "/";
                //MemoryStream ms = report.ExportPDF(MapPath("~"), qdCode);

                BUS.TestControl ctr = new BUS.TestControl();
                DTO.TestInfo inf = ctr.Get(Convert.ToInt64(Request["TestID"]), ref sErr);
                DTO.UserInfo usrinf = Session["UserGuest"] as DTO.UserInfo;
                DataSet dset = new DataSet();
                dset.Tables.Add(inf.ToDataTable());
                dset.Tables.Add(usrinf.ToDataTable());
                dset.Tables["Test"].Rows.Add(inf.ToDataRow(dset.Tables["Test"]));
                dset.Tables["TblUser"].Rows.Add(usrinf.ToDataRow(dset.Tables["TblUser"]));
                ReportGenerator rg = new ReportGenerator(dset, "CERTIFICATE", _db, _connDes, _pathTemp, _pathReport);

                using (MemoryStream ms = rg.ExportPDF(_pathTemp))
                {
                    ms.Position = 0;
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=CERTIFICATE-" + usrinf.Username + ".pdf");
                    Response.AddHeader("Content-Length", ms.Length.ToString());
                    Response.ContentType = "application/pdf";
                    Response.BinaryWrite(ms.ToArray());
                    Response.End();
                }
                //ExcelFile file = rg.ExportExcel(_pathReport);
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    file.Save(ms);
                //    ms.Position = 0;
                //    Response.Clear();
                //    Response.AddHeader("Content-Disposition", "attachment; filename=CERTIFICATE-" + usrinf.Username + ".xls");
                //    Response.AddHeader("Content-Length", ms.Length.ToString());
                //    Response.ContentType = "application/excel";
                //    Response.BinaryWrite(ms.ToArray());
                //    Response.End();
                //}
            }
        }

        protected void ckbAnswer_CheckedChanged(object sender, EventArgs arg)
        {
            DataSet dset = Session[_dsetName] as DataSet;
            int index = (int)Session["QuestIndex"];
            dset.Tables["dtQuest"].Rows[index]["IsAnswer"] = 1;
            ((CheckBox)sender).Enabled = false;
        }
        protected void rbAnswer_CheckedChanged(object sender, EventArgs arg)
        {
            btnHint_Click(null, null);
            DataSet dset = Session[_dsetName] as DataSet;
            int index = (int)Session["QuestIndex"];
            dset.Tables["dtQuest"].Rows[index]["IsAnswer"] = 1;
            dlAnswer.Enabled = false;
        }
        protected void txtAnswer_TextChanged(object sender, EventArgs arg)
        {
            DataSet dset = Session[_dsetName] as DataSet;
            int index = (int)Session["QuestIndex"];
            dset.Tables["dtQuest"].Rows[index]["IsAnswer"] = 1;
            ((TextBox)sender).Enabled = false;
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            if (Request["TestID"] != null)
            {
                _pathTemp = MapPath(_pathTemp) + "/";
                _pathReport = MapPath(_pathReport) + "/";
                //MemoryStream ms = report.ExportPDF(MapPath("~"), qdCode);

                BUS.TestControl ctr = new BUS.TestControl();
                DTO.TestInfo inf = ctr.Get(Convert.ToInt64(Request["TestID"]), ref sErr);
                DTO.UserInfo usrinf = Session["UserGuest"] as DTO.UserInfo;
                DataSet dset = new DataSet();
                dset.Tables.Add(inf.ToDataTable());
                dset.Tables.Add(usrinf.ToDataTable());
                dset.Tables["Test"].Rows.Add(inf.ToDataRow(dset.Tables["Test"]));
                dset.Tables["TblUser"].Rows.Add(usrinf.ToDataRow(dset.Tables["TblUser"]));
                ReportGenerator rg = new ReportGenerator(dset, "CERTIFICATE", _db, _connDes, _pathTemp, _pathReport);

                string content = "";
                using (TextWriter ms = rg.ExportHTML(_pathTemp))
                {
                    content = ms.ToString();
                }

                try
                {
                    Sendmail sm = new Sendmail();
                    if (usrinf.ANAL_U3 != "")
                    {
                        string[] arrMail = usrinf.ANAL_U3.Split(';');
                        for (int i = 0; i < arrMail.Length; i++)
                            sm.SendMail("ANI Vietnam e-learning", content, arrMail[i], true, true);
                    }

                    if (usrinf.Email != "")
                        sm.SendMail("ANI Vietnam e-learning", content, usrinf.Email, true, true);
                    //btnReset_Click(null, null);
                    //lbErr.Text = "Mail sent successfully";
                    btnSend.Enabled = false;
                }
                catch (Exception ex)
                {
                    //lbErr.Text = ex.Message;
                }
            }
        }

    }
}